package me.liuyu2783.dubbo.sample.http;

import org.apache.catalina.*;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.Tomcat;

/**
 * me.liuyu2783.dubbo.sample.tomcat
 *
 * @author liuyu2783
 * @date 2020-3-3
 */
public class HttpServer {

    private Tomcat tomcat;
    private String contextPath = "";

    public void start(int port){

        String hostname = "localhost";

        this.tomcat = new Tomcat();

        Service service = tomcat.getService();

        Connector connector = new Connector();
        connector.setPort(port);

        Engine engine = new StandardEngine();

        engine.setDefaultHost(hostname);

        Host host = new StandardHost();
        host.setName(hostname);

        Context context = new StandardContext();
        context.setPath(contextPath);
        context.addLifecycleListener(new Tomcat.FixContextListener());

        host.addChild(context);
        engine.addChild(host);

        service.setContainer(engine);
        service.addConnector(connector);

        tomcat.addServlet(contextPath,"dispatchServlet", new DispatchServlet());
        context.addServletMappingDecoded("/*","dispatchServlet");

        try {
            tomcat.getServer().start();
            tomcat.getServer().await();

        } catch (LifecycleException e) {
            e.printStackTrace();
        }
    }
}
